package com.wfh.easychat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.wfh.easychat.common.ErrorCode;
import com.wfh.easychat.exception.BusinessException;
import com.wfh.easychat.mapper.GroupInfoMapper;
import com.wfh.easychat.mapper.UserInfoMapper;
import com.wfh.easychat.model.entity.GroupInfo;
import com.wfh.easychat.model.entity.UserContact;
import com.wfh.easychat.model.entity.UserInfo;
import com.wfh.easychat.model.enums.UserContactStatusEnum;
import com.wfh.easychat.model.enums.UserContactTypeEnum;
import com.wfh.easychat.model.vo.UserContactVo;
import com.wfh.easychat.service.UserContactService;
import com.wfh.easychat.mapper.UserContactMapper;
import com.wfh.easychat.service.UserInfoService;
import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author fenghuanwang
* @description 针对表【user_contact(联系人)】的数据库操作Service实现
* @createDate 2025-09-29 18:19:23
*/
@Service
public class UserContactServiceImpl extends ServiceImpl<UserContactMapper, UserContact>
    implements UserContactService{



    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private UserContactMapper userContactMapper;

    @Resource
    private GroupInfoMapper groupInfoMapper;

    /**
     * 搜索用户或群组（公开查询，无需权限）
     *
     * @param id         当前用户 ID
     * @param contactId  目标 ID（用户ID 或 群ID）
     * @param typeId     类型：0-用户，1-群组
     */
    @Override
    public UserContactVo search(Long id, Long contactId, Integer typeId) {
        UserContactTypeEnum typeEnum = UserContactTypeEnum.getByType(typeId);
        if (typeEnum == null) {
            return null;
        }

        UserContactVo vo = new UserContactVo();
        vo.setContactId(contactId);
        vo.setContactType(typeEnum.getValue());

        switch (typeEnum) {
            case USER -> {
                // 1. 查询目标用户信息（公开）
                UserInfo userInfo = userInfoMapper.selectById(contactId);
                if (userInfo == null) {
                    // 用户不存在
                    return null;
                }
                vo.setNickName(userInfo.getNickName());
                vo.setGender(userInfo.getSex());
                vo.setAreaName(userInfo.getAreaName());

                // 2. 判断关系状态
                if (id.equals(contactId)) {
                    // 自己查自己
                    vo.setStatus(UserContactStatusEnum.FRIEND.getValue());
                    vo.setStatusName(UserContactStatusEnum.FRIEND.getDesc());
                } else {
                    // 查是否是当前用户的好友
                    boolean isFriend = userContactMapper.exists(
                            new LambdaQueryWrapper<UserContact>()
                                    .eq(UserContact::getId, id)                // 当前用户
                                    .eq(UserContact::getContactId, contactId)  // 目标用户
                                    .eq(UserContact::getContactType, UserContactTypeEnum.USER.getType())
                    );
                    if (isFriend) {
                        vo.setStatus(UserContactStatusEnum.FRIEND.getValue());
                        vo.setStatusName(UserContactStatusEnum.FRIEND.getDesc());
                    } else {
                        vo.setStatus(null); // 或设为 0，根据前端约定
                        vo.setStatusName("非好友");
                    }
                }
            }

            case GROUP -> {
                // 直接查询群信息（公开）
                GroupInfo groupInfo = groupInfoMapper.selectById(contactId);
                if (groupInfo == null) {
                    return null; // 群不存在
                }
                vo.setNickName(groupInfo.getGroupName());
                // 群无性别/地区
                vo.setStatus(null);
                vo.setStatusName("正常");
            }

            default -> {
                return null;
            }
        }

        return vo;
    }

    /**
     * 添加好友申请
     * @param loginUser
     * @param contactId
     * @param applyInfo
     * @param type
     * @return
     */
    @Override
    public Integer applyAdd(UserInfo loginUser, Long contactId, String applyInfo, Integer type) {
        UserContactTypeEnum byType = UserContactTypeEnum.getByType(type);
        if (byType == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        // 申请人
        Long userId = loginUser.getId();
        Long groupOwnerId = null;
        Integer joinType = null;
        // 查询对方好友是否已经添加，如果拉黑了就无法添加
        MPJLambdaWrapper<UserContact> wrapper = new MPJLambdaWrapper<UserContact>()
                .innerJoin(UserInfo.class, UserInfo::getId, UserContact::getId)
                .eq(UserContact::getContactId, contactId);
        UserContact userContact = userContactMapper.selectJoinOne(wrapper);
        if (userContact == null && UserContactStatusEnum.BLACKLIST_BE.getValue().equals(userContact.getStatus())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "你已经被对方拉黑");
        }
        if (UserContactTypeEnum.GROUP == byType){
            GroupInfo groupInfo = groupInfoMapper.selectById(contactId);
            if (groupInfo == null || groupInfo.getStatus().equals(0)){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "群聊不存在或已解散");
            }
            groupOwnerId = groupInfo.getGroupOwner();
            joinType = groupInfo.getJoinType();
        }else {
            UserInfo userInfo = userInfoMapper.selectById(contactId);
            if (userInfo == null){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "联系人不存在");
            }
            joinType = userInfo.getJoinType();
        }

        return 0;
    }
}




